﻿using Compass.Wasm.Shared.Wms;
using Compass.Wpf.ApiServices.Wms;
using System.Collections.Generic;
using Application = Microsoft.Office.Interop.Excel.Application;

namespace Compass.Wpf.ViewModels.Wms;

public class VendorsViewModel : NavigationViewModel
{
    #region ctor
    private readonly IVendorService _vendorService;
    public VendorsViewModel(IContainerProvider provider) : base(provider)
    {
        _vendorService = provider.Resolve<IVendorService>();

        VendorDto = new VendorDto();
        AddVendorCommand = new DelegateCommand(AddVendor);
        UpdateVendorCommand = new DelegateCommand<VendorDto>(UpdateVendor);
        DeleteVendorCommand = new DelegateCommand<VendorDto>(DeleteVendor);
        SaveVendorCommand = new DelegateCommand(SaveVendor);

        OpenCsvCommand = new DelegateCommand(OpenCsv);
        UpdateCommand = new DelegateCommand<string>(Update);
        UpdateRoles = "admin,whse,pur";
    }
    private string updateRoles;
    public string UpdateRoles
    {
        get => updateRoles;
        set { updateRoles = value; RaisePropertyChanged(); }
    }
    public DelegateCommand AddVendorCommand { get; }
    public DelegateCommand<VendorDto> UpdateVendorCommand { get; }
    public DelegateCommand<VendorDto> DeleteVendorCommand { get; }
    public DelegateCommand SaveVendorCommand { get; }

    public DelegateCommand OpenCsvCommand { get; }
    public DelegateCommand<string> UpdateCommand { get; }
    #endregion

    #region 右侧展开栏属性
    private bool isRightDrawerOpen;
    /// <summary>
    /// 右侧窗口是否展开
    /// </summary>
    public bool IsRightDrawerOpen
    {
        get => isRightDrawerOpen;
        set { isRightDrawerOpen = value; RaisePropertyChanged(); }
    }
    private string rightDrawerTitle = null!;
    public string RightDrawerTitle
    {
        get => rightDrawerTitle;
        set { rightDrawerTitle = value; RaisePropertyChanged(); }
    }

    #endregion

    #region 属性
    private string search;
    /// <summary>
    /// 搜索条件属性
    /// </summary>
    public string Search
    {
        get => search;
        set
        {
            search = value;
            RaisePropertyChanged();
            Filter();
        }
    }

    private VendorDto vendorDto;
    public VendorDto VendorDto
    {
        get => vendorDto;
        set { vendorDto = value; RaisePropertyChanged(); }
    }
    public ObservableRangeCollection<VendorDto> VendorDtos { get; } = new();
    public ObservableRangeCollection<VendorDto> FilterVendorDtos { get; } = new();

    #endregion

    #region 增删改查
    private void AddVendor()
    {
        VendorDto = new VendorDto();

        IsRightDrawerOpen = true;
        RightDrawerTitle = "添加供应商";
    }

    private void UpdateVendor(VendorDto obj)
    {
        VendorDto = obj;

        IsRightDrawerOpen = true;
        RightDrawerTitle = "修改供应商";
    }

    private async void DeleteVendor(VendorDto obj)
    {
        //删除询问
        var dialogResult = await DialogHost.Question("删除确认", $"确认删除供应商：{obj.Name}, {obj.Remarks} 吗?");
        if (dialogResult.Result != ButtonResult.OK) return;
        await _vendorService.DeleteAsync(obj.Id.Value);
        GetDataAsync();
    }

    private async void SaveVendor()
    {
        //数据验证
        if (string.IsNullOrWhiteSpace(VendorDto.Number))
        {
            //发送提示
            Aggregator.SendMessage("供应商编号不能为空");
            return;
        }

        try
        {
            //VendorDto.Name =VendorDto.Name.ToUpper();
            if (VendorDto.Id != null && VendorDto.Id.Value != Guid.Empty)
            {
                
                await _vendorService.UpdateAsync(VendorDto.Id.Value, VendorDto);
                Aggregator.SendMessage($"供应商：{VendorDto.Name}修改成功！");
                VendorDto.Id = Guid.Empty;
            }
            else
            {
                var dto = await _vendorService.GetSingleByNumberAsync(VendorDto.Number);
                if (dto.Status)
                {
                    Aggregator.SendMessage($"请不要重复添加，供应商：{VendorDto.Name}！");
                    return;
                }
                await _vendorService.AddAsync(VendorDto);
                Aggregator.SendMessage($"供应商：{VendorDto.Name}添加成功！");
                VendorDto.Id = Guid.Empty;
            }
            IsRightDrawerOpen = false;
            GetDataAsync();
        }
        catch (Exception e)
        {
            //发送错误报告
            Aggregator.SendMessage(e.Message);
        }
    }
    #endregion

    #region 打开CSV文件，更新列表
    private void OpenCsv()
    {
        var path = System.IO.Path.Combine(Environment.CurrentDirectory, "Vendor.csv");
        var excelApp = new Application();
        excelApp.Workbooks.Open(path);
        excelApp.Visible = true;
    }

    private async void Update(string obj)
    {
        var path = System.IO.Path.Combine(Environment.CurrentDirectory, "Vendor.csv");
        List<VendorString> vendors;
        try
        {
            vendors = path.GetRecords<VendorString>();
        }
        //StreamReader的异常
        catch (Exception e)
        {
            Aggregator.SendMessage($"请关闭Excel后再执行更新，{e.Message}");
            return;
        }
        var dtos = (await _vendorService.GetAllAsync()).Result;
        foreach (var itemDto in vendors)
        {
            //判断编号是否相同
            var dto = dtos.FirstOrDefault(x => x.Number.Equals(itemDto.Number)) ?? new VendorDto { Id = Guid.Empty };
            //更新基本信息，没有则添加，有则修改
            dto.Number = itemDto.Number;
            dto.Name = itemDto.Name;
            dto.Contact = itemDto.Contact;
            dto.Address = itemDto.Address;
            dto.Telephone = itemDto.Telephone;
            dto.Remarks = itemDto.Remarks;

            if (dto.Id == Guid.Empty)
            {
                await _vendorService.AddAsync(dto);
            }
            else
            {
                await _vendorService.UpdateAsync(dto.Id.Value, dto);
            }
        }
        Aggregator.SendMessage("更新完毕！");
        GetDataAsync();
    } 
    #endregion
    
    #region 筛选
    private void Filter()
    {
        FilterVendorDtos.ReplaceRange(
            VendorDtos.Where(x =>
                string.IsNullOrEmpty(Search) ||
                x.Number.Contains(Search, StringComparison.OrdinalIgnoreCase) ||
                x.Name.Contains(Search, StringComparison.OrdinalIgnoreCase) ||
                !string.IsNullOrEmpty(x.Contact) && x.Contact.Contains(Search, StringComparison.OrdinalIgnoreCase) ||
                !string.IsNullOrEmpty(x.Remarks) && x.Remarks!.Contains(Search, StringComparison.OrdinalIgnoreCase)).Take(100));
    }
    #endregion

    #region 导航初始化
    private async void GetDataAsync()
    {
        var result = await _vendorService.GetAllAsync();
        if (!result.Status) return;
        VendorDtos.ReplaceRange(result.Result);
        Filter();
    }
    public override void OnNavigatedTo(NavigationContext navigationContext)
    {
        base.OnNavigatedTo(navigationContext);
        GetDataAsync();
    }
    #endregion
}